var Chat = {
	detailInit: function() {
		var toObj = GetLS("groupchat_detail");
		var data = {};
		data.groupid = toObj._id;
		var ajaxAfterFun = function(items, user){
			// setTimeout(tmoFun, 1000*2);
			var html = Chat.gnHtml(items, user);
			$("#ctn").append(html);
			if (html != "")
				$(document).scrollTop($(document).height());
		}
		var tmoFun = function(){
			$ajaxT({
				url: "/groupmessage/detail",
				data: data,
				success: function(res) {
				    ajaxAfterFun(res.result, toObj);
				}
			});
		};
		tmoFun();

	},
	send: function() {
		var msgcontent = $("#msg").val();
		if (msgcontent == "") {
		  (CurrentUser.category==30?$alert("留言内容不能为空"):$alertEn("The message can not be empty"));
			return;
		}
		$("#msg").val("");

		var toObj = GetLS("groupchat_detail");
		var data = {};
		data.from = CurrentUser._id;
		data.groupid=toObj._id;
		data.media = 0;
		data.content = msgcontent;
    	$ajax({
			url: "/groupmessage/add",
			data: data,
			success: function(res) {
				CCall("Chat.sendAppend('" + JSON.stringify(res.result) + "')");
			}
		});
	},
	sendPhoto: function() {
		Upload.init(Core.API_VER + "/upload?compress=1", function(res) {
			res = res[0];
		 	if (res.code) {
		 		$alert(res.codemsg);
		 		return;
		 	}

			var toObj = GetLS("chat_detail");
			var data = {};
			data.from = CurrentUser._id;
			data.to = toObj._id;
			data.media = 1;
			data.content = res.result.url;

			$ajax({
				url: "/message/add",
				data: data,
				success: function(res) {
					Chat.sendAppend(JSON.stringify(res.result));
				}
			});
		});
	},
	sendAppend: function(item) {
		item = JSON.parse(item);
		var html = Chat.gnHtml(new Array(item), "self");
		$("#ctn").append(html);
		if (html != "")
			$(document).scrollTop($(document).height());
	},
	gnHtml: function(items, user) {
		var html = "";
		var flag = false;
		if (Chat.lastID && user != "self")
			flag = true;
		for (var i = 0; i < items.length; ++i) {
			if (flag) {
				if (items[i]._id == Chat.lastID)
					flag = false;
				continue;
			}
			var content = "";

			if (items[i].from == CurrentUser._id) {
				if (items[i].media == 0 ) {
					content = '	<div class="talk_ctn" style="float:right">' +
								'      	<div class="uc-a upp5 wb_a talk_ctn right umw3 uml_2" style="float:none;" ontouchstart="zy_touch(\'talk_ctn_act\', undefined, \'longpress\')" onclick="Appcan.copy(\''+ items[i].mcontent +'\');">' +
								'         	<div class="uwp5 uh1 ub_img im_talk_right"></div>' + items[i].content +
								'     	</div>' +
								'	<div class="ufp8 tx-r">' + Core.offsetDate(items[i].create) + '</div>' +
								'</div>';
				}else if (items[i].media == 1) {
					content = '<div class="uw7 uh5 ub_img photoBrowserEvent" data-url="'+ items[i].content +'" style="background-image:url('+ Core.id2url(items[i].content, "thumbnail") +'); background-size:cover; float:right" ontouchstart="zy_touch()" onclick="ImageBrowser(\'' + items[i].content + '\')"></div>';
				}
				html += '<div class="ub-f1 ub uptb_p5">' +
					'	 <div class="uw3"></div>' +
					'    <div class="ub-f1 upr_1">' + content +
					'    </div>' +
					'    <div class="uw3 uh3 umar-tp5 ub_img100 uc-a" style="background-image:url(\'' + Core.id2url(CurrentUser) + '\');"></div>' +
					'</div>';
			} else {
				if (items[i].media == 0&&CurrentUser.category==20) {
					content = '<div class="talk_ctn">' +
							  '		<div class="ub uc-a upp5 wb_a talk_ctn left umw3 umar-r2" style="" ontouchstart="zy_touch(\'talk_ctn_act\', undefined, \'longpress\')" onclick="Appcan.copy(\''+ items[i].content +'\');">' +
							  '			<div class="uwp5 uh1 ub_img im_talk_left"></div>' + items[i].content +
							  '			<div class="ub-img im_icon_translate-t uw1p5 uh1p5 ump05" ontouchstart="zy_touch()" onclick="Chat.translate(\'' + items[i].content + '\')"></div>' + 
							  '		</div>' +
							  '		<div id="fanyi" class="ufp8"></div>' + 
							  '		<div class="ufp8 tx-l">' + Core.offsetDate(items[i].create) + '</div>' +
							  '</div>';
				}else if(items[i].media == 0 &&CurrentUser.category==30){
				   content = '<div class="talk_ctn">' +
                              '     <div class="ub uc-a upp5 wb_a talk_ctn left umw3 umar-r2" style="" ontouchstart="zy_touch(\'talk_ctn_act\', undefined, \'longpress\')" onclick="Appcan.copy(\''+ items[i].content +'\');">' +
                              '         <div class="uwp5 uh1 ub_img im_talk_left"></div>' + items[i].content +
                              '         <div class="ub-img im_icon_translate uw1p5 uh1p5 ump05" ontouchstart="zy_touch()" onclick="Chat.translate(\'' + items[i].content + '\')"></div>' + 
                              '     </div>' +
                              '     <div id="fanyi" class="ufp8"></div>' + 
                              '     <div class="ufp8 tx-l">' + Core.offsetDate(items[i].create) + '</div>' +
                              '</div>'; 
				}else if (items[i].media == 1) {
					content = '<div class="uw7 uh5 ub_img photoBrowserEvent" data-url="'+ items[i].content +'" style="background-image:url('+ Core.id2url(items[i].content, "thumbnail") +'); background-size:cover;" ontouchstart="zy_touch()" onclick="ImageBrowser(\'' + items[i].content + '\')"></div>';
				}
				html += '<div class="ub-f1 ub uptb_p5">' +
					'    <div class="uw3 uh3 umar-tp5 ub_img100 uc-a" style="background-image:url(\'' + Core.id2url(GetLS("chat_detail")) + '\');"></div>' +
					'    <div class="ub-f1 upl_1">' + content +
					'    </div>' +
					'	 <div class="uw3"></div>' +
					'</div>';
			}
		}
		if (items[items.length-1] != undefined)
			Chat.lastID = items[items.length-1]._id;
		return html;
	},
	//翻译功能
	translate: function(str){
		var $this = $(event.currentTarget);
		event.stopPropagation();
		$ajax({
			url: "/fanyi",
			data:{
				content: str
			},
			success: function(res){
				$this.parent().next("#fanyi").text(res.result.result);
			}
		});
	},//删除并退出群
	    removeGroup: function(){
	    uexWindow.confirm(CurrentUser.category==30?"警告":"Warning",CurrentUser.category==30?"确定要删除吗？":"Do you want to detete?",CurrentUser.category==30?"确定,取消":"Sure,Cancel");
        function cbConfirm(opId, dataType, ensure){
            if(ensure == 0){
                var group = GetLS("alist_gdetail");
                var toObj = GetLS("groupchat_detail");
                var userid = new Array();
                var user_id = CurrentUser._id;
                userid.push(user_id);
                $ajax({
                    url: "/group/removeGroup",
                    data: {
                        groupKeyId:toObj._id,
                        userid:userid,
                        id:user_id
                    },
                    success: function(res) {
                        //PCall("grouplist","CCall('Alist.removeRow()')");
                        PCall("grouplist","WinClose()");
                        PCall("groupchat_detail","WinClose()"); 
                        PCall("friendgroup_detail","WinClose()"); 
                        //PCall("friendSearchList","WinClose()");       
                        //WinClose();
                    }
                });
            }
        }
        uexWindow.cbConfirm = cbConfirm;     
    },//删除好友
        removeFriends: function(removeId){
        uexWindow.confirm(CurrentUser.category==30?"警告":"Warning",CurrentUser.category==30?"确定要删除吗？":"Do you want to detete?",CurrentUser.category==30?"确定,取消":"Sure,Cancel");
        function cbConfirm(opId, dataType, ensure){
            if(ensure == 0){
                
                var toObj = GetLS("groupchat_detail");
                var userid = new Array();
                //获取删除人的id数组
                userid.push(""+removeId);
                $ajax({
                    url: "/group/removeFriendsFromGroup",
                    data: {
                        groupKeyId:toObj._id,
                        userid:userid,
                    },
                    success: function(res) {
                       Chat.groupDetailInit(1);
                      
                    }
                });
            }
        }
        uexWindow.cbConfirm = cbConfirm;     
    },
    /**修改群名字*/
       toUpdateGroupName: function (){
        OpenNewWin("add_groupchat");
    },
    /**群详情初始化 flag=1标示删除群用户,isFirst:是不是首次初始化*/
   groupDetailInit:function(flag){
      var toObj = GetLS("groupchat_detail");
      var groupName = toObj.name;
      if(toObj.userid== CurrentUser._id){
          var deleteObj = $("#delete").html();
              if(deleteObj==undefined){
              var removeHtml= '<div id="delete" class="ub uh3 uw3 headImg" style="background-image: url(../img/delete_03.png); background-size: 100% 100%;" onclick="Chat.clickRemove();"></div>';
              Chat.isFirst==false;
              $("#addBehind").append(removeHtml);  
          }

      }
      $("#groupName").text(groupName);
      /**获取群中好友信息：头像，名称，主键_id*/
        $ajax({
        url: "/group/getUserListByGroupId",
        data: {
            groupKeyId:toObj._id
        },
        success: function(res) {
            SetLS("GroupUserLists",res.result);
            var users= res.result;
            var html="";
            var first = '<div class="ub uw100 headImgDiv" >'; 
            var last = '</div><div class="ub uw100 headImgDiv" style="margin-top:0px">';
            for(var i=0;i<users.length;i++){
                if(i==0){
                    html = html+first;
                }else if(i!=0&&(i%4==0)) {
                     html = html+last;
                }
                //begin if
             if(i!=users.length-1){
             html=html+
            '<div class="ub ub-ver headImg">'+
               '<div class="ub uh3 uw3" style="background-image: url('+Core.id2url(users[i])+'); background-size: 100% 100%;position:relative;">';
               if(toObj.userid!=users[i]._id){
                html=html+ '<div class="editImg hide uh1 uw1" onclick="Chat.removeFriends(\''+users[i]._id+'\');"   style="position:absolute;left:-10px;top:-10px;background-image: url(../img/remove.png); background-size: 100% 100%;"></div>';  
               }
               
               html=html+'</div>'+
                '<div class="ub ub-ac ub-pc" style="margin-top: 13%; font-size: 0.9em;">'+users[i].name+'</div>'+
            '</div>';
                
              }  else{
               html=html+
              '<div class="ub ub-ver headImg headImgLast">'+
               '<div class="ub uh3 uw3" style="background-image: url('+Core.id2url(users[i])+'); background-size: 100% 100%;position:relative;">';
              if(toObj.userid!=users[i]._id){
                html=html+ '<div class="editImg hide uh1 uw1" onclick="Chat.removeFriends(\''+users[i]._id+'\');"   style="position:absolute;left:-10px;top:-10px;background-image: url(../img/remove.png); background-size: 100% 100%;"></div>';  
               }
               
               html=html+'</div>'+
                '<div class="ub ub-ac ub-pc" style="margin-top: 13%; font-size: 0.9em;">'+users[i].name+'</div>'+
                '</div>';
              
              } //end else
            }//end for 
            html=html+'</div>';
            $("#friendList").html(html);
           var bodyWidth = $("body").width();
            var headImgWidth = $(".headImg").width();
            var width = (bodyWidth-4*headImgWidth)/5;
            $(".headImg").css("margin-left", width);
            $(".headImgLast").css("margin-right", width);
            $(".headImgDiv").css({"padding-top":width});
            $(".headEditDiv").css({"padding-top":width,"padding-bottom":width});
            if(flag==1){
                 $(".editImg").toggleClass("hide");
            }
        }
    });
   },
   onlyAddFriend:function(){
       //仅仅添加好友
       SetLS("addFriendFlag","onlyAdd");
       OpenNewWin("friendSearchList");
   },
   //点击删除好友的-号时
   clickRemove:function(){
    $(".editImg").toggleClass("hide");
   },
   //点击添加好友的+号时
   clickAdd:function(){
       Chat.onlyAddFriend();
   },
   //修改群名称
   modifyGroupName:function(groupName){
       $("#groupName").text(groupName);
   },
   //刷新当前页面
   refreshPage:function(){
       window.location.reload();
   }
   

}